package com.example.ui.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.example.ui.dto.TranExcel;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据库导出连云港文件，匹配服务包信息，筛选出empiid相等的
 */
public class LYGUtils {

    public final static String LYG_EXCEL_PATH = "C:\\Users\\yliu\\Desktop\\trans\\连云港.csv";

    public final static String EMPI_ID_EXCEL_FILE_PATH = "C:\\Users\\yliu\\Downloads\\query-hive-49965.xlsx";

    public final static String EXCEL_PATH = "C:\\Users\\yliu\\Desktop\\writeMapTest.xlsx";

    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void readLYGExcel() {
        CsvReader reader = CsvUtil.getReader();
        List<TranExcel> tranExcels = reader.read(ResourceUtil.getReader(LYG_EXCEL_PATH, CharsetUtil.CHARSET_GBK), TranExcel.class);


    }

    public static void readBZExcel() {
        ExcelReader reader = ExcelUtil.getReader(FileUtil.file(EMPI_ID_EXCEL_FILE_PATH));
        List<Map<String, Object>> readAll = reader.readAll();
        CsvReader csvReader = CsvUtil.getReader();
        List<TranExcel> tranExcels = csvReader.read(ResourceUtil.getReader(LYG_EXCEL_PATH, CharsetUtil.CHARSET_GBK), TranExcel.class);
        ExcelWriter writer = ExcelUtil.getWriter("C:\\Users\\yliu\\Desktop\\writeMapTest.xlsx");
        for (Map<String, Object> stringObjectMap : readAll) {
            for (TranExcel tranExcel : tranExcels) {
                if (stringObjectMap.get("empiid").equals(tranExcel.getEmpi_id())) {
                    Map<String, Object> row1 = new LinkedHashMap<>();
                    row1.put("name", stringObjectMap.get("name"));
                    row1.put("empiid", stringObjectMap.get("empiid"));
                    List<TranExcel.Tran> trans = JSON.parseArray(tranExcel.getTrans_text(), TranExcel.Tran.class);
                    trans.removeIf(transText -> ("个案师".equals(transText.getSpeaker()) || "A".equals(transText.getSpeaker())));
                    StringBuffer speakerText = new StringBuffer();
                    trans.forEach(tran -> {
                        speakerText.append(tran.getText()).append(",");
                    });
                    row1.put("trans_text", speakerText);
                    ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1);
                    writer.write(rows);
                }
            }
        }
// 关闭writer，释放内存
        writer.close();

    }

    private static ThreadLocal<ExcelWriter> threadLocalWriter = ThreadLocal.withInitial(() -> ExcelUtil.getWriter("D:/test.xlsx"));


    public static void main(String[] args) {
//        readAndWrite();
//        ExcelWriter writer = ExcelUtil.getWriter(FileUtil.file("D:/test.xlsx"));
//        Map<String, Object> row1 = new LinkedHashMap<>();
//        row1.put("name", "name");
//        row1.put("empiid", "empiid");
//        row1.put("trans_text", "transText");
//        row1.put("result","templateC");
//        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1);
//        writer.write(rows);
//        writer.close();
//        merge();
        mergeResult();
    }


    public static void readAndWrite() {
        ExcelReader reader = ExcelUtil.getReader(FileUtil.file(EXCEL_PATH));
        List<Map<String, Object>> readAll = reader.readAll();
        AtomicInteger count = new AtomicInteger(0);
        for (Map<String, Object> stringObjectMap : readAll) {
            executor.execute(() -> {
                try {

                    ExcelWriter writer = ExcelUtil.getWriter("D:/TEST/test" + count + ".xlsx");
                    count.incrementAndGet();
                    String name = (String) stringObjectMap.get("name");
                    String transText = (String) stringObjectMap.get("trans_text");
                    String templateA = OpenUtils.templateA(transText, name);
                    String templateB = OpenUtils.templateB(templateA, name);
                    String templateC = OpenUtils.templateC(templateB, name);
                    Map<String, Object> row1 = new LinkedHashMap<>();
                    row1.put("name", stringObjectMap.get("name"));
                    row1.put("empiid", stringObjectMap.get("empiid"));
                    row1.put("trans_text", transText);
                    row1.put("result", templateC);
                    ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1);
                    writer.write(rows);
                    writer.close();
                    System.out.println("excel写入。。。test" + count);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        reader.close();
        executor.shutdown();
    }


    public static void merge() {
        int count = 0;
        ExcelWriter writer = ExcelUtil.getWriter("D:/TESTS/merge.xlsx");
        for (int i = 0; i <= 672; i++) {
            try {
                ExcelReader reader = ExcelUtil.getReader("D:/TEST/test" + count++ + ".xlsx");
                List<Map<String, Object>> readAll = reader.readAll();
                for (Map<String, Object> stringObjectMap : readAll) {
                    String name = (String) stringObjectMap.get("name");
                    String empiid = (String) stringObjectMap.get("empiid");
                    String transText = (String) stringObjectMap.get("trans_text");
                    String result = (String) stringObjectMap.get("result");
                    Map<String, Object> row1 = new LinkedHashMap<>();
                    row1.put("name", name);
                    row1.put("empiid", empiid);
                    row1.put("trans_text", transText);
                    row1.put("result", result);
                    ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1);
                    writer.write(rows);
                }
                reader.close();
            } catch (Exception e) {
                System.err.println("文件不存在跳过");
            }

        }
        writer.close();
    }

    public static void mergeResult() {
        ExcelReader reader = ExcelUtil.getReader("D:/TESTS/merge.xlsx");
        HashMap<String, String> map = new HashMap<>(32);
        List<Map<String, Object>> readAll = reader.readAll();
        for (Map<String, Object> stringObjectMap : readAll) {
            String name = (String) stringObjectMap.get("病种");
            String result = (String) stringObjectMap.get("患者录音转文字");
            map.put(name, Objects.isNull(map.get(name)) ? result : map.get(name) + result);
        }
        System.out.println("字符拼接完毕");
        System.out.println("map结果：" + map);
        reader.close();
        ExcelWriter writer = ExcelUtil.getWriter("D:/TESTS/result2.xlsx");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String result = OpenUtils.templateA(entry.getValue(), entry.getKey());
            String result1 = OpenUtils.templateC(result, entry.getKey());
            Map<String, Object> row1 = new LinkedHashMap<>();
            row1.put("病种", entry.getKey());
            row1.put("gpt结果", result1);
            ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1);
            writer.write(rows);
            writer.flush();
            System.out.println("写入excel。。。");
        }
        writer.close();

    }

    public static void plan() {
        ExcelReader reader = ExcelUtil.getReader("C:\\Users\\yliu\\Desktop\\writeMapTest.xlsx");
        List<Map<String, Object>> readAll = reader.readAll();

    }


}
